// ~/middleware/auth.global.ts (全局中间件)
import { useUserStore } from "@/store";
import tool from "@/utils/tool";
import NProgress from "nprogress";

const whiteRoute = ["masterlogin", "merchantlogin"];

export default defineNuxtRouteMiddleware(async (to) => {
  const userStore = useUserStore();
  const config = useRuntimeConfig();
  const token = tool.local.get(config.public.VITE_APP_TOKEN_PREFIX);
  const defaultRoutePath = "/dashboard"; // 进度条处理
  if (process.client) {
    NProgress.start();
  } // 登录状态处理
  if (token) {
    if (to.name === "login" || to.name === "index") {
      return navigateTo(defaultRoutePath);
    }

    let allRouters = userStore.routers;
    if (!userStore.user) {
      const data = await userStore.requestUserInfo();
      allRouters = userStore.routers;
      if (data) {
        return navigateTo(to.fullPath);
      }
    }
    const all: string[] = [];
    allRouters &&
      allRouters.forEach(({ children, path }: any) => {
        if (children.length === 0) {
          all.push(path);
        }
        children.forEach((item: any) => {
          all.push(item.path);
        });
      });

    if (!all.includes(to.path) && !whiteRoute.includes(to.path)) {
      return navigateTo("/error");
    }
  } else {
    if (!whiteRoute.includes(to.name as string)) {
      //如何拿到当前路由的路径
      console.log(to.fullPath);
      const path = to.fullPath.split("/").pop();
      return navigateTo({
        name: `${path}login`,
        query: { redirect: to.fullPath },
      });
    }
  }
});
